import { PublishLaya2Base } from "./PublishLaya2Base";
import { join } from "path";
import { IPublishVo, IProjectVo } from "../data/Config";
import { existsSync, readFileSync, writeFileSync } from "fs";
import { createDirSync, cpFile } from "../utils/FileUtil";
let path = require("path");

export class OppoPublish extends PublishLaya2Base {
    get projDir() { return "oppogame"; }
    get libJs() { return "laya.quickgamemini.js"; }
    private _isDebug: boolean;
    init(publishVo: IPublishVo, projectInfo: IProjectVo) {
        super.init(publishVo, projectInfo);
        this._isDebug = !this._publishVo.content.chkRelease;
    }


    async createProject() {
        this.log("初始化工具项目目录(第一次初始化比较慢，请耐心等待)");
        await this.exec("npm i", { cwd: this.mTempProjPath, shell: true });
        if (!existsSync(this.mProjPath)) {
            createDirSync(this.mProjPath);
        }
        await this.doPack();
    }

    async doPack() {
        await this.buildProject();
        await this._copyIcon();
        await this._copySign();
        this._createMainFast();
        await this._buildRpk();
        this.packOver();
    }

    private async _copyIcon() {
        if (this._publishVo.content && this._publishVo.content.icon) {
            cpFile(this._publishVo.content.icon, path.join(this.mProjPath, "image", path.basename(this._publishVo.content.icon)));
        }
        this.log("复制icon");
    }

    private async _copySign() {
        this.log("复制签名");
        if (!this._isDebug) {
            if (this._publishVo.content && this._publishVo.content.cert) {
                await this.copyDir(this._publishVo.content.cert, path.join(this.mProjPath, "sign\/release"));
            } else {
                this.log("正式版秘钥不能为空");
            }
        }
    }

    private _createMainFast() {
        // 修改manifest.json文件
        let manifestPath = path.join(this.mProjPath, "manifest.json");
        let IDEManifestPath = path.join(this.mTempProjPath, "tpl", "manifest.json");
        if (!existsSync(IDEManifestPath)) {
            return;
        }
        let manifestContent = readFileSync(IDEManifestPath, "utf8");
        let manifestJson = JSON.parse(manifestContent);
        manifestJson.package = this._publishVo.content.appId;
        manifestJson.name = this._publishVo.content.name || this.mProjectInfo.name;
        // manifestJson.orientation = config.vivoInfo.orientation;
        manifestJson.config.logLevel = this._isDebug ? "debug" : "off";
        // manifestJson.deviceOrientation = config.vivoInfo.orientation;
        manifestJson.versionName = this._version;
        manifestJson.versionCode = this._publishVo.content.versionCode;
        manifestJson.minPlatformVersion = Number(this._publishVo.content.minSdkVersion || "1040");
        manifestJson.icon = `/image/${path.basename(this._publishVo.content.icon)}`;
        delete manifestJson.subpackages;
        writeFileSync(manifestPath, JSON.stringify(manifestJson, null, 4), "utf8");
        // 修改game.js文件
        let content = `window.navigator.userAgent = 'Mozilla/5.0 (Linux; Android 5.1.1; Nexus 6 Build/LYZ28E) AppleWebKit/603.1.30 (KHTML, like Gecko) Mobile/14E8301 OPPO MiniGame NetType/WIFI Language/zh_CN'
require("./libs/${this.libJs}");\nrequire("./config.js");\nrequire("./index.js");`;
        let gameJsPath = path.join(this.mProjPath, "main.js");
        writeFileSync(gameJsPath, content, "utf8");

        // vivo项目，修改index.js
        let filePath = path.join(this.mProjPath, "index.js");
        if (!existsSync(filePath)) {
            return;
        }
        let fileContent = readFileSync(filePath, "utf8");
        fileContent = fileContent.replace(/loadLib(\(['"])/gm, "require$1./");
        writeFileSync(filePath, fileContent, "utf8");
    }

    private async _buildRpk() {
        let cmd = "\"" + path.join(this.mTempProjPath, "lib", "bin", `quickgame.cmd`) + "\"";
        cmd += " pack";
        if (!this._isDebug) {
            cmd += " release";
        }
        await this.exec(cmd, { cwd: this.mProjPath });
    }

    async showPreView() {
        await this.exec(`adb push dist/${this._publishVo.content.appId}${!this._isDebug ? ".signed" : ""}.rpk sdcard/games`, { cwd: this.mProjPath, shell: true });
        let oppoPropPath = path.join(this.mTempProjPath, `instant_app_settings.properties`);
        writeFileSync(oppoPropPath, "default_tab_index=2", "utf8");
        await this.exec(`adb push ${oppoPropPath} sdcard/`, { cwd: this.mProjPath, shell: true });
        await this.exec(`adb shell am start -n com.nearme.instant.platform/com.oppo.autotest.main.InstantAppActivity`, { cwd: this.mProjPath, shell: true });
    }

    getEngineVersion() {
        let workSpaceDir = this._publishVo.fromPath;
        let coreLibPath = path.join(workSpaceDir, "libs", "laya.core.js");
        let isHasCoreLib = existsSync(coreLibPath);
        let EngineVersion;
        if (isHasCoreLib) {
            let con = readFileSync(coreLibPath, "utf8");
            let matchList = con.match(/Laya\.version\s*=\s*['"]([0-9\.]+(beta)?.*)['"]/);
            if (!Array.isArray(matchList)) {
                return null;
            }
            EngineVersion = matchList[1];
        }
        return EngineVersion;
    }

    protected mWriteConfig() {
        writeFileSync(join(this.mProjPath, this.getConfigName()), "window.config = " + this.config + ";");
    }
}